package com.se.service;

import cn.hutool.core.util.IdUtil;
import com.se.dao.mysql.UserDao;
import com.se.domain.dto.wx.WxUserAccessTokenDTO;
import com.se.domain.dto.wx.WxUserInfoDTO;
import com.se.domain.mysql.UserDO;
import com.se.exception.ResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AuthService {
    @Autowired
    WxOpenService wxOpenService;
    @Autowired
    UserDao userDao;
    public Long loginTest(Long userId) {
        if(userDao.existByUserId(userId)){
            return userId;
        }else {
            return null;
        }
    }

    public String generateAndStoreUserToken(Long userId) {
        if(userId == null){
            throw new NullPointerException();
        }
        String uuid = IdUtil.simpleUUID();
        userDao.storeUserIdUuidInRedis(userId, uuid);
        return uuid+"@"+userId;
    }

    public Long loginByCode(String code) throws ResultException {
        WxUserAccessTokenDTO accessTokenDTO = wxOpenService.getUserAccessTokenByCode(code);
        UserDO userDO = userDao.getByOpenId(accessTokenDTO.getOpenid());
        if(userDO == null){
            Long userId = userDao.createByOpenId(accessTokenDTO.getOpenid());
            this.initWxUserInfo(userId, accessTokenDTO.getAccessToken(),accessTokenDTO.getOpenid());
            return userId;
        }
        return userDO.getUserId();
    }


    @Async("wxAsyncExecutor")
    void initWxUserInfo(Long userId, String accessToken, String openId) throws ResultException {
        WxUserInfoDTO wxUserInfoDTO = wxOpenService.getUserInfo(accessToken, openId);
        String username = wxUserInfoDTO.getNickname();
        String headImgUrl = wxUserInfoDTO.getHeadImgUrl();
        userDao.updateWxUserInfo(userId, username, headImgUrl);
    }

    public Long getUserIdFromToken(String userToken){
        //检查是否为空
        if(userToken == null){
            return null;
        }
        String uuid;
        Long userId;
        try {
            String[] split = userToken.split("@");
            uuid = split[0];
            userId = Long.valueOf(split[1]);
        }catch (Throwable e){
            return null;
        }
        if(Objects.equals(uuid, userDao.getUUIDbyUserIdFromRedis(userId))){
            return userId;
        }
        return null;
    }
}
